import time

import numpy as np
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import os

# 浏览器启动选项
option = webdriver.ChromeOptions()
# option.page_load_strategy = 'none'  # 设置 pageLoadStrategy 为 "none" (也就是非阻塞)
# # 这行代码可以解决无界面模式下，读不出某些载具的问题，idk why LOL
option.add_argument("--window-size=1920,1080")
# # 指定为无界面模式
# option.add_argument('--headless')
driver = webdriver.Chrome(options=option)

driver.get("https://squadmaps.com")
xpath = '//section'

elems = driver.find_elements(By.XPATH, xpath)
# print(len(elems), type(elems[0]))
map_elems = driver.find_elements(By.XPATH, '//section')
map_elems = map_elems[1:] # 去掉最顶上没用的section

for i in range(len(map_elems)): # 遍历每一张地图
    i += 2 # 从2开始遍历

    map_name = driver.find_element(By.XPATH, '//section[' + str(i) + ']').get_attribute('id')

    mode_xpath = xpath + "[@id='" + map_name + "']/div/div"
    print('chk:', mode_xpath)
    mode_elems = driver.find_elements(By.XPATH, mode_xpath)

    for j in range(len(mode_elems)): # 遍历每一种模式
        elem_mode_xpath = mode_xpath + '[' + str(j + 1) + ']/h3'
        # print(elem_mode_xpath)
        each_elem = driver.find_element(By.XPATH, elem_mode_xpath)
        mode_name = each_elem.text

        # 找到阵营按钮并点击
        show_info_button_xpath = elem_mode_xpath + "/../a[@class='vehicles']"
        print(show_info_button_xpath)
        show_info_button = driver.find_element(By.XPATH, show_info_button_xpath)
        driver.execute_script("arguments[0].click();", show_info_button)
        time.sleep(3)
        # 找队名
        team1_elem = driver.find_element(By.XPATH, '//h3[@id="modal_team_1_name"]')
        team2_elem = driver.find_element(By.XPATH, '//h3[@id="modal_team_2_name"]')
        team1_name, team2_name = team1_elem.text, team2_elem.text # 得到两队队名
        # print(team1_elem.text, team2_elem.text)

        # 找载具信息
        list1_element = driver.find_elements(By.XPATH, "//div[@class='modal_side'][1]/ul/li")
        list2_element = driver.find_elements(By.XPATH, "//div[@class='modal_side'][2]/ul/li")
        # print(len(list1_element), len(list2_element))
        print(map_name, mode_name)
        team1_list, team2_list = [], [] # 把两队载具放入列表，等待后续保存
        for elem in list1_element:
            team1_list.append(elem.text[1:])
        for elem in list2_element:
            team2_list.append(elem.text[1:])

        temp_dict = {}
        temp_dict[team1_name] = team1_list
        temp_dict[team2_name] = team2_list
        # print('chk :', './data' + '/' + map_name + '/' + mode_name)
        print(temp_dict)
        np.save('./data' + '/' + map_name + '/' + mode_name + '/car_info.npy', temp_dict)

        driver.refresh()
        time.sleep(1)
        # os.mkdir('./data/' + map_name + '/' + mode_name) # 新建模式文件夹

        
